﻿#include "MainWindow.h"

#include <ctkPluginContext.h>
#include <ctkPluginException.h>
#include <ctkPluginFramework.h>
#include <ctkPluginFrameworkLauncher.h>
#include <service/event/ctkEventAdmin.h>

#include <QApplication>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QDirIterator>
#include <QDockWidget>
#include <QJsonObject>
#include <QMessageBox>
#include <QPushButton>
#include <QSettings>
#include <QStringList>
#include <QStringLiteral>
#include <QTextEdit>
#pragma execution_character_set("utf-8")  // 解决界面中文乱码问题
#include <QThread>

#include "./Base/data.h"
#include "ui_MainWindow.h"

Q_DECLARE_METATYPE(data);

MainWindow::MainWindow(QWidget* parent)
    : SARibbonMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);

  setDockNestingEnabled(true);  // 允许使用dock

  InitPluginFrameWork();
  InitMenuAndActions();
  LoadPlugins();
  setRibbonTheme(SARibbonTheme::RibbonThemeOffice2021Blue);

  InitDockManager();

  this->resize(1920, 1080);
}

MainWindow::~MainWindow() {}

void MainWindow::InitPluginFrameWork() {
  QString current_dir = QApplication::applicationDirPath();
  ctkPluginFrameworkLauncher::addSearchPath(current_dir +
                                            "/plugins/CTKPlugins/");
  ctkPluginFrameworkLauncher::start("org.commontk.eventadmin");

  framework_ = frame_work_factory_.getFramework();
  try {
    // 初始化并启动插件框架
    framework_->init();
    framework_->start();
  } catch (const ctkPluginException& e) {
    qDebug() << "Failed to initialize the plugin framework: " << e.what();
    qDebug() << e.message() << e.getType();
  }

  // 获取插件服务的contex
  plugin_context_ = framework_->getPluginContext();
}

void MainWindow::LoadPlugins() {
  QString current_dir = QApplication::applicationDirPath();

  try {
    LoadPluginsInDirectory(current_dir +
                           "/plugins/AppPlugins/EventListenerPlugin/");
    LoadPluginsInDirectory(current_dir +
                           "/plugins/AppPlugins/EventPublisherPlugin/");
  } catch (const ctkPluginException& e) {
  }
}

void MainWindow::LoadPluginsInDirectory(const QString& plugins_dir) {
  QDirIterator it(plugins_dir, QStringList() << "*.dll",
                  QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);

  while (it.hasNext()) {
    LoadAndStartPlugin(it.next());
  }
}

void MainWindow::LoadAndStartPlugin(const QString& plugin_path) {
  try {
    qDebug() << "plugin_path:" << plugin_path;
    plugin_ = plugin_context_->installPlugin(QUrl::fromLocalFile(plugin_path));
    qDebug() << QString("Plugin[%1 v%2] installed...")
                    .arg(plugin_->getSymbolicName())
                    .arg(plugin_->getVersion().toString());

    // 启动插件
    plugin_->start(ctkPlugin::START_TRANSIENT);

  } catch (const ctkPluginException& e) {
    qDebug() << QString("Failed to install or run plugin: ") << e.what();
  }
}

void MainWindow::InitDockManager() {
  // 获取所有插件服务
  QList<ctkServiceReference> serviceRefs =
      plugin_context_->getServiceReferences<IDockWidget>();

  for (const ctkServiceReference& serviceRef : serviceRefs) {
    qDebug() << "获取-------------------";
    IDockWidget* dockWidget =
        plugin_context_->getService<IDockWidget>(serviceRef);
    if (dockWidget) {
      QWidget* widget = dockWidget->CreateWidget();

      qDebug() << dockWidget->GetDockObjectName();
      if (dockWidget->GetDockObjectName() == "PublisherPluginDockWidget") {
        this->setCentralWidget(widget);

      } else {
        QDockWidget* pDock =
            new QDockWidget(dockWidget->GetDockObjectName(), this);
        pDock->setWidget(widget);

        pDock->show();

        this->addDockWidget(Qt::RightDockWidgetArea, pDock);
      }
      dockWidget->InitWidget();
    }
    // 不要忘记在不需要服务时释放
    plugin_context_->ungetService(serviceRef);
  }
}
int is_1 = 0;
void MainWindow::InitMenuAndActions() {
  ribbon_bar_ = ribbonBar();
  // QWidget模式下，没有必要再显示标题
  ribbon_bar_->setTitleVisible(false);
  ribbon_bar_->setApplicationButton(nullptr);
  ribbon_bar_->setRibbonStyle(SARibbonBar::RibbonStyleLooseThreeRow);

  SARibbonCategory* file_category = ribbon_bar_->addCategoryPage(tr("文件"));
  SARibbonPannel* pannel1 = file_category->addPannel(("Panel 1"));
  QAction* actSave = new QAction(this);
  actSave->setText("save");
  actSave->setIcon(QIcon(":/icon/resource/icon/save.svg"));
  actSave->setObjectName("actSave");
  actSave->setShortcut(QKeySequence(QLatin1String("Ctrl+S")));
  pannel1->addSmallAction(actSave);

  SARibbonCategory* file_category2 = ribbon_bar_->addCategoryPage(tr("其他"));
  SARibbonPannel* pannel2 = file_category2->addPannel(("Panel 2"));
  QAction* actSave2 = new QAction(this);
  actSave2->setText("save1");
  actSave2->setIcon(QIcon(":/icon/resource/icon/save.svg"));
  actSave2->setObjectName("actSave2");
  actSave2->setShortcut(QKeySequence(QLatin1String("Ctrl+A")));
  pannel2->addMediumAction(actSave2);

  SARibbonCategory* file_category3 = ribbon_bar_->addCategoryPage(tr("11"));

  connect(actSave, &QAction::triggered, [=]() {
    switch (is_1) {
      case 0:
        setRibbonTheme(SARibbonTheme::RibbonThemeOffice2013);
        break;

      case 1:
        setRibbonTheme(SARibbonTheme::RibbonThemeOffice2016Blue);
        break;

      case 2:
        setRibbonTheme(SARibbonTheme::RibbonThemeOffice2021Blue);
        break;

      case 3:
        setRibbonTheme(SARibbonTheme::RibbonThemeWindows7);
        break;
      case 4:
        setRibbonTheme(SARibbonTheme::RibbonThemeDark);
        break;
      default:
        break;
    }
    is_1++;
    is_1 %= 5;
  });
}

void MainWindow::SendEvent(const QString topic, const ctkDictionary& dict) {
  ctkServiceReference ref;
  ctkEventAdmin* eventAdmin{nullptr};
  ref = plugin_context_->getServiceReference<ctkEventAdmin>();
  if (ref) {
    eventAdmin = plugin_context_->getService<ctkEventAdmin>(ref);
    plugin_context_->ungetService(ref);
  }

  if (eventAdmin) {
    eventAdmin->postEvent(ctkEvent(topic, dict));
  }
}
